package com.idea.relax.boot.security.xss;

import lombok.AllArgsConstructor;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @className: XssRequestFilter
 * @description:
 * @author: salad
 * @date: 2023/4/5
 **/
@AllArgsConstructor
public class XssRequestFilter implements Filter {

	private final RelaxXssProperties xssProperties;

	private final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
		String path = ((HttpServletRequest) request).getServletPath();
		if (!xssProperties.isEnabled() || isSkipUrl(path)) {
			chain.doFilter(request, response);
		}
		//XSS过滤
		XssHttpServletRequestWrapper requestWrapper = new XssHttpServletRequestWrapper((HttpServletRequest)request);
		chain.doFilter(requestWrapper, response);
	}

	private boolean isSkipUrl(String path) {
		return xssProperties.getSkipUrls().stream().anyMatch(pattern -> ANT_PATH_MATCHER.match(pattern, path));
	}


}
